package binarycrew.livewallpapers.utils;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import binarycrew.livewallpapers.Preferences;

public class PreferenceHelper {

	private static final String TAG = "PreferenceHelper";

	public static String[] getSourceUrls(SharedPreferences preferences) {

		String source_urls = preferences.getString(Preferences.SOURCE_URL_PREFS, null);
		if (source_urls == null || source_urls.equals("")) {
			return new String[] {};
		}
		else {
			return source_urls.split(",");
		}
	}

	public static boolean addToSourceUrls(String url, SharedPreferences preferences) {
		String[] urls = getSourceUrls(preferences);
		if (contains(urls, url))
			return false;

		Editor editor = preferences.edit();

		StringBuilder pref_string = new StringBuilder();
		pref_string.append(url);

		for (int i = 0; i < urls.length; i++) {
			pref_string.append("," + urls[i]);
		}

		Log.d(TAG, "set preferences: " + pref_string.toString());
		editor.putString(Preferences.SOURCE_URL_PREFS, pref_string.toString());
		return editor.commit();
	}

	public static boolean removeFromSourceUrls(String url, SharedPreferences preferences) {
		String[] urls = getSourceUrls(preferences);
		if (!contains(urls, url))
			return false;

		Editor editor = preferences.edit();

		StringBuilder pref_string = new StringBuilder();

		for (int i = 0; i < urls.length; i++) {
			if (urls[i].equals(url) == false)
				pref_string.append(urls[i] + ",");
		}

		if (pref_string.length() > 0)
			pref_string.deleteCharAt(pref_string.length() - 1);

		Log.d(TAG, "set preferences: " + pref_string.toString());
		editor.putString(Preferences.SOURCE_URL_PREFS, pref_string.toString());
		return editor.commit();
	}

	public static boolean adjustSourceUrlsByKey(String key, String url, SharedPreferences preferences) {
		boolean value = preferences.getBoolean(key, false);
		if (value == true) {
			return addToSourceUrls(url, preferences);
		}
		else {
			return removeFromSourceUrls(url, preferences);
		}
	}

	private static boolean contains(String[] array, String value) {
		for (int i = 0; i < array.length; i++) {
			if (array[i].equals(value))
				return true;
		}
		return false;
	}

}
